#pragma once
#include <list>
#include <memory>
#include <nice2d/sprite.h>
#include <nice2d/component.h>

template<class T>
class SpritePool : public Component
{
public:
    SpritePool()
    {
        static_assert(std::is_base_of<Sprite, T>::value);
    }
public:
    void setCreator(std::function<std::shared_ptr<T>()> creator)
    {
        spriteCreator = creator;
        assert(spriteCreator);
    }
    std::shared_ptr<T> createOrAwakeSprite()
    {
        auto itr = sprites.begin();
        while (itr != sprites.end()) {
            auto sprite = *itr;
            if (sprite->getSpriteStatus() == SPRITE_STATUS_DEATH) {
                sprite->setSpriteStatus(SPRITE_STATUS_DEATH);
                return sprite;
            }
            itr ++;
        }

        return addSprite();
    }

    auto addSprite() -> std::shared_ptr<T>
    {
        std::shared_ptr<T> sprite = nullptr;
        if (spriteCreator)
            sprite = spriteCreator();
        else
            sprite = std::make_shared<T>();

        sprite->setSpriteStatus(1);
        sprites.push_back(sprite);
        return sprite;
    }
private:
    std::function<std::shared_ptr<T>()> spriteCreator;
    std::list<std::shared_ptr<T>> sprites;
};
